# coding=utf-8
# 代码文件：chapter2/ch2.7.py
import time

import cv2
import pytesseract as tess
from PIL import Image
from selenium import webdriver

driver = webdriver.Firefox()
strLoginURL = 'http://127.0.0.1:5000/'


# loginPress函数用于登录处理
def loginpress():
    # ----处理验证码-----------

    # 获得验证码图片img元素控件
    imgelement = driver.find_element_by_id("vcodeimage")

    driver.save_screenshot("tmp/1.png")  # 截取屏幕图片

    location = imgelement.location      # 获取图片坐标
    size = imgelement.size              # 获图片大小

    # 设置截取图片区域，指定四个参数，左上角坐标和右下角坐标。
    rangle = int(location['x']), int(location['y']), int(location['x'] + size['width']), int(
        location['y'] + size['height'])

    # 打开截取屏幕的图片
    imgcode = Image.open('tmp/1.png')
    # 使用crop函数截取图片
    result = imgcode.crop(rangle)
    # 保存截取后的图片
    result.save('tmp/2.png')

    # 调用identifycode函数识别验证码
    vcode = identifycode('tmp/2.png')

    print("识别验证码:", vcode)

    # 获得身份证号文本框对象
    element = driver.find_element_by_id("userid")
    # 清除文本框内容
    element.clear()
    # 模拟在文本框输入内容
    element.send_keys('123')
    element = driver.find_element_by_id("userpwd")
    element.clear()
    element.send_keys('456')

    # 获得验证码输入框对象
    element = driver.find_element_by_id("vcode")
    # 清除输入框内容
    element.clear()
    # 模拟单击登录按钮
    element.send_keys(vcode)

    # 获得登录按钮元素
    btnElement = driver.find_element_by_class_name("loginbtn")
    # 模拟单击登录按钮
    btnElement.click()
    spanElement = driver.find_element_by_id("message")
    msg = spanElement.text
    print(msg)
    if msg == '验证码输入错误！':
        # 当前线程休眠2秒钟
        time.sleep(2)
        # 再次请求验证码
        # 调用loginPress函数登录处理
        loginpress()
    if msg == '登录成功！':
        pass


''' 验证码识别函数，参数是要识别的图片路径 '''
def identifycode(imagefilePath):
    # 1.读取图片
    src_image = cv2.imread(imagefilePath)
    # 2.转为灰度化图像
    gray_image = cv2.cvtColor(src_image, cv2.COLOR_BGR2GRAY)
    # 3.转为二值化图像
    th_image = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 21, 2)

    pil_image = Image.fromarray(th_image)
    # 转文本显示
    text = tess.image_to_string(pil_image)

    vcode = text.strip().replace(' ', '')  # 删除字符串前后空白，并替换字符串中的空格

    return vcode


if __name__ == '__main__':
    # 发送网络请求
    driver.get(strLoginURL)
    # 调用loginPress函数登录处理
    loginpress()
